package com.renjibo.cicledemomath;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

/**
 * 任继波
 * Created by Administrator on 2017/3/1.
 */

public class MyView extends View {

    private float height;
    private float width;
    private String text;
    private float renInCicle;
    private float renOnCicle;
    private Paint mPaint;
    private int i;
    private int j;

    public MyView(Context context) {
        this(context,null);
    }

    public MyView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyView);
        height = typedArray.getDimension(R.styleable.MyView_renheight, getY());
        width = typedArray.getDimension(R.styleable.MyView_renWidth, getX());
        text = typedArray.getString(R.styleable.MyView_renText);
        renInCicle = typedArray.getDimension(R.styleable.MyView_renInCicle, 10);
        renOnCicle = typedArray.getDimension(R.styleable.MyView_renOnCicle, 20);
        mPaint = new Paint();

}

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        i = getWidth() / 2;
        j = getHeight() / 2;
        float x = event.getX();
        float y = event.getY();
        float abs = Math.abs(x - i);
        float abs1 = Math.abs(y - j);
        //开方
        double sqrt = Math.sqrt(abs * abs + abs1 * abs1);
        if(sqrt<renInCicle){
            Log.d("zzz","内圆");
        }else if(sqrt<renOnCicle){
            Log.d("zzz","外圆");
        }else{
            Log.d("zzz","正方形");
        }
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.save();
        mPaint.setColor(Color.BLUE);
        canvas.drawCircle(getWidth()/2,getHeight()/2,renOnCicle,mPaint);
        canvas.restore();

        canvas.save();
        mPaint.setColor(Color.RED);
        canvas.drawCircle(getWidth()/2,getHeight()/2,renInCicle,mPaint);
        canvas.restore();

        canvas.save();
        mPaint.setColor(Color.WHITE);

        Rect mbounds=new Rect();
        mPaint.getTextBounds(text,0,text.length(),mbounds);//文本范围

        canvas.drawText(text,getWidth()/2-mbounds.width()/2,getHeight()/2+mbounds.height()/2,mPaint);
        canvas.restore();
    }
}
